layui.define(['table', 'form'], function(exports){
  var $ = layui.$,table = layui.table,form = layui.form;

    $('#userId').select2({
        placeholder: "请选择设备归属人",
        width: '250px',
        theme: 'bootstrap',
        allowClear : true,
        ajax: {
            url: layui.setter.webRoot + '/agent/select.data',
            method: 'post',
            delay: 250,
            processResults: function (result) {
                if (result.code == 200) {
                    return {
                        pagination: {more: result.body.more},
                        results: result.body.data || []
                    };
                } else {
                    return {results: []};
                }
            }
        }
    });

  table.render({
    elem: '#LAY-table'
    ,url: layui.setter.webRoot + '/device/list.data'
    ,method: 'post'
    ,parseData: function (res) {
        return {
            "code": res.code,
            "msg": res.msg,
            "count": res.body.total,
            "data": res.body.data
        };
    }
    ,response: {statusCode: 200}
    ,cols: [[
      {type: 'checkbox', fixed: 'left'}
      ,{field: 'deviceSn', title: '设备序列号'}
      ,{field: 'deviceTypeId',title: '设备类型',templet:function(record){
                  return record.deviceTypeName + '('+ record.deviceTypeId+')';
              }}
      ,{field: 'deviceFunNames', title: '设备功能名称'}
      ,{field: 'batchId', title: '生产批次'}
      ,{field: 'userInfo',title: '所属人'}
      ,{field: 'placeId',title: '部署网点',templet:function(record){
          if(record.placeId) {
              return record.placeName + '(' + record.placeId + ')';
          }else{
              return '--';
          }
       }}
      ,{field: 'stateName', title: '设备状态',templet:function (record){
          if(record.state == 2){
              return '<span class="layui-badge layui-bg-green">'+record.stateName+'</span>';
          }
          return record.stateName;
      }}
      ,{field: 'deployDate', title: '部署时间'}
      ,{field: 'createDate', title: '创建时间'}
      ,{title: '操作', width: 220, align: 'center', fixed: 'right', templet: function (record) {
              var html = '<a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="info">查看</a>';
                  html = html + '<a class="layui-btn layui-btn-xs" lay-event="qrcode">二维码</a>';
              if(record.placeId){
                  html = html + ' <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="remove">移除部署</a>';
              }else{
                  html = html + ' <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>';
              }
              return html;
          }}
    ]]
    ,page: true
    ,limit: 30
    ,height: 'full-220'
    ,text: '对不起，加载出现异常！'
  });
  
  //监听搜索
  form.on('submit(LAY-search)', function(data){
    var field = data.field;
    //执行重载
    table.reload('LAY-table', {
      where: field
      ,page: {curr: 1}
    });
  });
  
  $('#btnSearch').click();
  
  //事件
  var active = {
      add:function(){
          layer.open({
              type: 2
              , title: '新增设备'
              , content: layui.setter.webRoot + '/device/add.html'
              , maxmin: false
              , area: ['500px', '400px']
              , btn: ['确定', '取消']
              , yes: function(index, layero){
                  var iframeWindow = window['layui-layer-iframe'+ index]
                      ,submitID = 'LAY-form-submit'
                      ,submit = layero.find('iframe').contents().find('#'+ submitID);
                  iframeWindow.layui.form.on('submit('+ submitID +')', function(data){
                      var field = data.field;
                      $.ajax({
                          type: "post",
                          url: layui.setter.webRoot + '/device/add.do',
                          data:field,
                          dataType:"json",
                          success:function(res){
                              if(res.code == 200){
                                  layer.close(index);
                                  table.reload('LAY-table');
                                  layer.msg('新增成功',{icon: 1});
                              }else{
                                  layer.msg(res.msg,{icon: 2});
                              }
                          }
                      });
                  });
                  submit.trigger('click');
              }
          });
      }
     ,info:function(obj){
    	layer.open({
            type: 2
            ,title: '查看设备详情'
            ,content: layui.setter.webRoot + '/device/info.html?deviceSn='+obj.data.deviceSn
            ,maxmin: true
            ,area: ['90%', '90%']
          });
      }
     ,remove:function(obj){
          parent.layer.confirm('确定要移除该设备部署吗？', function(index){
              $.ajax({
                  type: "post",
                  url: layui.setter.webRoot + '/place/device/undeploy.do',
                  data:{deviceSn:obj.data.deviceSn},
                  dataType:"json",
                  success:function(res){
                      if(res.code == 200){
                          obj.del();
                      }else{
                          parent.layer.msg(res.msg,{icon: 5});
                      }
                  }
              });
              parent.layer.close(index);
          });
      }
     ,del:function(obj){
    	layer.confirm('确定要删除该设备吗？', function(index){
	    	$.ajax({
	      	  type: "post",
	          url: layui.setter.webRoot + '/device/del.do',
	          data:{deviceSn:obj.data.deviceSn},
	  		  dataType:"json",
	  		  success:function(res){
	  			if(res.code == 200){
	  				obj.del();
	  			}else{
	  				layer.msg(res.msg,{icon: 5});
	  			}
	  		  }
	        });
	    	layer.close(index);
	    });
    }
    ,qrcode: function (obj) {
          layer.open({
              type: 2
              , title: '设备二维码'
              , content: layui.setter.webRoot + '/device/qrcode.html?deviceSn=' + obj.data.deviceSn
              , maxmin: false
              , area: ['400px', '450px']
              , btn: ['取消']
          });
      }
	,setBelong:function (obj){
		var checkStatus = table.checkStatus('LAY-table'),checkData = checkStatus.data; //得到选中的数据
		var ids = '';
	    if(checkData.length === 0){
	      	return layer.msg('请选择要设置设备！');
	    }else{
	    	$(checkData).each(function(i,e){ids = ids + ',' + e.deviceSn;});
	    	ids = ids.substring(1);
	    }
		
		$.ajax({
			type: "post",
	        url: layui.setter.webRoot + '/device/produce/batch/device/belong/cache.do',
	        data:{deviceSnListStr:ids},
	        dataType:"json",
	        success:function(res){
	          if(res.code == 200){
				layer.open({
		              type: 2
		              , title: '设置设备所属人'
		              , content: layui.setter.webRoot + '/device/produce/batch/device/belong/set.html'
		              , maxmin: false
		              , area: ['500px', '550px']
		              , btn: ['确定', '取消']
		              , yes: function(index, layero){
		                  var iframeWindow = window['layui-layer-iframe'+ index]
		                      ,submitID = 'LAY-form-submit'
		                      ,submit = layero.find('iframe').contents().find('#'+ submitID);
		                  iframeWindow.layui.form.on('submit('+ submitID +')', function(data){
		                      var field = data.field;
		                      $.ajax({
		                          type: "post",
		                          url: layui.setter.webRoot + '/device/produce/batch/device/belong/set.do',
		                          data:field,
		                          dataType:"json",
		                          success:function(res){
		                              if(res.code == 200){
		                                  layer.close(index);
		                                  table.reload('LAY-table');
		                                  layer.msg('设置成功',{icon: 1});
		                              }else{
		                                  layer.msg(res.msg,{icon: 2});
		                              }
		                          }
		                      });
		                  });
		                  submit.trigger('click');
		              }
		          });
	          }else{
	              layer.msg(res.msg,{icon: 2});
	          }
	        }
	    });
	 }
  	,removeBelong:function (obj){
		var checkStatus = table.checkStatus('LAY-table'),checkData = checkStatus.data; //得到选中的数据
		var ids = '';
        if(checkData.length === 0){
          	return layer.msg('请选择要移除设备！');
        }else{
        	$(checkData).each(function(i,e){ids = ids + ',' + e.deviceSn;});
        	ids = ids.substring(1);
        }
		
		$.ajax({
			type: "post",
	        url: layui.setter.webRoot + '/device/produce/batch/device/belong/cache.do',
	        data:{deviceSnListStr:ids},
	        dataType:"json",
	        success:function(res){
              if(res.code == 200){
				layer.open({
		              type: 2
		              , title: '移除设备所属人'
		              , content: layui.setter.webRoot + '/device/produce/batch/device/belong/remove.html'
		              , maxmin: false
		              , area: ['500px', '400px']
		              , btn: ['确定', '取消']
		              , yes: function(index, layero){
		                  var iframeWindow = window['layui-layer-iframe'+ index]
		                      ,submitID = 'LAY-form-submit'
		                      ,submit = layero.find('iframe').contents().find('#'+ submitID);
		                  iframeWindow.layui.form.on('submit('+ submitID +')', function(data){
		                      var field = data.field;
		                      $.ajax({
		                          type: "post",
		                          url: layui.setter.webRoot + '/device/produce/batch/device/belong/remove.do',
		                          data:field,
		                          dataType:"json",
		                          success:function(res){
		                              if(res.code == 200){
		                                  layer.close(index);
		                                  table.reload('LAY-table');
		                                  layer.msg('移除成功',{icon: 1});
		                              }else{
		                                  layer.msg(res.msg,{icon: 2});
		                              }
		                          }
		                      });
		                  });
		                  submit.trigger('click');
		              }
		          });
              }else{
                  layer.msg(res.msg,{icon: 2});
              }
	        }
	    });
     }
  };
  
  $('.layui-btn.LAY-btn-fun').on('click', function(){
    var type = $(this).data('type');
    active[type] ? active[type].call(this) : '';
  });
  
  table.on('tool(LAY-table)', function(obj){
  	var type = obj.event ;
   	active[type] ? active[type].call(this,obj) : '';
  });
  
  exports('device_list', {})
});